﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Yakool.Order
{
    class AnalysisTask : ITask
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private SpiderContext context;

        public AnalysisTask(SpiderContext ctx)
        {
            context = ctx;
        }

        public void RunSynchronously()
        {
            using (var s = new StreamWriter(context.OutputFile, false, Encoding.UTF8))
            {
                s.WriteLine(CreateCsvHeader());

                foreach (var order in context.Order["resultsList"])
                {
                    s.WriteLine(ToCsv(order));
                }
            }
            log.InfoFormat("CSV file {0} created", context.OutputFile);
            Process.Start(context.OutputFile);
        }

        private string CreateCsvHeader()
        {
            var sb = new StringBuilder();

            sb.Append("订单号");
            sb.Append(',');
            sb.Append("订单状态");
            sb.Append(',');
            sb.Append("订单描述");
            sb.Append(',');
            sb.Append("件数");
            sb.Append(',');
            sb.Append("订单金额");
            sb.Append(',');
            sb.Append("支付方式");
            sb.Append(',');
            sb.Append("非返利支付金额");
            sb.Append(',');
            sb.Append("返利支付金额");
            sb.Append(',');
            sb.Append("订单返利");
            sb.Append(',');
            sb.Append("下单时间");
            sb.Append(',');
            sb.Append("付款时间");
            sb.Append(',');
            sb.Append("最迟送货日期");
            sb.Append(',');
            sb.Append("购买人");
            sb.Append(',');
            sb.Append("备注");
            sb.Append(',');
            sb.Append("对方收货人");
            sb.Append(',');
            sb.Append("对方收货人手机");
            sb.Append(',');
            sb.Append("对方收货人电话");
            sb.Append(',');
            sb.Append("小区");
            sb.Append(',');
            sb.Append("门牌号");
            //sb.Append(',');

            return sb.ToString();
        }

        private string ToCsv(JToken order)
        {
            var sb = new StringBuilder();

            sb.Append(order["purchaseOrderId"]);
            sb.Append(',');
            sb.Append(HumanizeOrderStatus((int)order["status"]));
            sb.Append(',');
            sb.Append(N(order["productBrief"]));
            sb.Append(',');
            sb.Append(N(order["productNum"]));
            sb.Append(',');
            sb.Append(HumanizeOrderPayment((int)order["needPayAmount"]));
            sb.Append(',');
            sb.Append(HumanizeOrderPaymentMode((int)order["paymentMode"]));
            sb.Append(',');
            sb.Append("--"); //非返利支付金额
            sb.Append(',');
            sb.Append(HumanizeOrderPayment((int)order["yakoolCoin"]));
            sb.Append(',');
            sb.Append(HumanizeOrderPayment((int)order["integral"]));
            sb.Append(',');
            sb.Append(HumanizeOrderTime((long)order["createdTimestamp"]));
            sb.Append(',');
            sb.Append(HumanizeOrderTime((long)order["purchaseOrderInfo"]["payupTimestamp"] * 1000));
            sb.Append(',');
            sb.Append("--"); //最迟送货日期
            sb.Append(',');
            sb.Append(N(order["buyerName"]));
            sb.Append(',');
            sb.Append(N(order["purchaseOrderInfo"]["remark"]));
            sb.Append(',');
            sb.Append(N(order["receiverName"]));
            sb.Append(',');
            sb.Append(N(order["mobilePhone"]));
            sb.Append(',');
            sb.Append(N(order["telephone"]));
            sb.Append(',');
            sb.Append(N(order["community"]));
            sb.Append(',');
            sb.Append(N(order["houseNumber"]));
            //sb.Append(',');

            return sb.ToString();
        }

        private string N(JToken token)
        {
            return token.ToString().Replace(',', ':');
        }

        private string HumanizeOrderTime(long ticks)
        {
            return new DateTime(1970, 1, 1, 8, 0, 0, 0).AddMilliseconds(ticks).ToString();
        }

        // http://yakool-home.com/backend/js/purchaseorder/customerpurchaseorder.js#693
        private string HumanizeOrderPaymentMode(int mode)
        {
            switch (mode)
            {
                case 1: return "返利支付";
                case 3:
                case 4: return "货到付款";
                case 201: return "支付宝";
                default: return "网银支付";
            }
        }

        private string HumanizeOrderPayment(int payment)
        {
            return (payment / 100.0).ToString("N");
        }


        static Dictionary<int, string> _dict = new Dictionary<int, string>
            {
                {1,"等待支付押金"},
                {2,"等待付款"},
                {3,"已付款"},
                {15,"配货中"},
                {4,"物品待打包"},
                {5,"物品已打包"},
                {6,"已发货"},
                {7,"交易成功"},
                {8,"客户退单"},
                {9,"等待会员确认"},
                {10,"已收货"},
                {11,"无效订单"},
                {12,"配货中"},
                {13,"部分发货"},
                {20,"购物车"},
                {21,"订单筹备中"},
                {22,"订单被删除状态"},
                {23,"配货中"}
            };
        // http://yakool-home.com/backend/js/purchaseorder/customerpurchaseorder.js#505
        private string HumanizeOrderStatus(int status)
        {
            if (_dict.ContainsKey(status))
            {
                return _dict[status];
            }
            return "";

            //switch (status)
            //{
            //    case 1: return "等待支付押金";
            //    case 2: return "等待付款";
            //    case 3: return "配货中";
            //    case 6: return "已发货";
            //    case 7: return "交易成功";
            //    case 9: return "等待会员确认";
            //    case 10: return "已收货";
            //    case 11: return "无效订单";
            //    case 12: return "配货中";
            //    case 13: return "部分发货";
            //    case 22: return "订单被删除状态";
            //    case 23: return "配货中";
            //    default: return "订单正在处理中";
            //}
        }
    }
}
